/*******************************************************************************
 * Copyright (c) 2001, 2009 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.googlecode.viewt.plugin.ui.internal.editor;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.DefaultEditDomain;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.MouseWheelHandler;
import org.eclipse.gef.MouseWheelZoomHandler;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.gef.editparts.LayerManager;
import org.eclipse.gef.editparts.ZoomManager;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.actions.ZoomInAction;
import org.eclipse.gef.ui.actions.ZoomOutAction;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.MultiPageEditorPart;
//import org.eclipse.wst.sse.ui.StructuredTextEditor;
import org.googlecode.viewt.plugin.ui.internal.adt.design.DesignViewGraphicalViewer;
import org.googlecode.viewt.plugin.ui.internal.adt.design.editparts.RootContentEditPart;
import org.googlecode.viewt.plugin.ui.internal.adt.design.editparts.RootEditPart;

public class ConstantMultiPageEditor extends MultiPageEditorPart implements
		IPropertyListener {

	//private StructuredTextEditor structuredTextEditor;

	private ScrollingGraphicalViewer graphicalViewer;

	protected DefaultEditDomain editDomain;

//	protected IModel model;
	
	
	public ConstantMultiPageEditor() {
		super();
		editDomain = new DefaultEditDomain(this) {
			public void mouseDown(MouseEvent mouseEvent, EditPartViewer viewer) {
				boolean eatTheEvent = false;
				LayerManager manager = (LayerManager) viewer
						.getEditPartRegistry().get(LayerManager.ID);
				IFigure layer = manager.getLayer("Scaled Handle Layer");
				if (layer != null) {
					Point p = new Point(mouseEvent.x, mouseEvent.y);
					layer.translateToRelative(p);
					IFigure figure = layer.findFigureAt(p);
					if (figure != null && figure != layer) {
						// we eat this selection event!
						eatTheEvent = true;
					}
				}
				if (!eatTheEvent) {
					super.mouseDown(mouseEvent, viewer);
				}
			}
		};
	}

	@Override
	protected void createPages() {

//		 selectionProvider = getSelectionManager();

		createGraphPage();
		createSourcePage();

		// getEditorSite().setSelectionProvider(selectionProvider);
		//
//		 model = buildModel(); // (IFileEditorInput)getEditorInput());
		//		    
		 initializeGraphicalViewer();
		// floatingToolbar.setModel(model);
		//		    
		// int pageIndexToShow = getDefaultPageTypeIndex();
		// setActivePage(pageIndexToShow);
	}

	protected void initializeGraphicalViewer()
	  {
	    RootContentEditPart root = new RootContentEditPart();
//	    if (!(getEditorInput() instanceof IADTEditorInput))
//	    {
//	      root.setModel(model);
//	    }
	    graphicalViewer.setContents(root);
	  }
	  
	
	private void createGraphPage() {
		Composite parent = createGraphPageComposite();

		graphicalViewer = getGraphicalViewer();
		graphicalViewer.createControl(parent);

		 getEditDomain().addViewer(graphicalViewer);
		//
		 configureGraphicalViewer();
//		 hookGraphicalViewer();
		int index = addPage(parent);
		setPageText(index, "Design");
	    
	}
	
	 protected void configureGraphicalViewer()
	  {
	    graphicalViewer.getControl().setBackground(ColorConstants.listBackground);

	    // Set the root edit part
	    // ScalableFreeformRootEditPart root = new ScalableFreeformRootEditPart();
	    RootEditPart root = new RootEditPart();
	    ZoomManager zoomManager = root.getZoomManager();
//	    
	    List zoomLevelContributions = new ArrayList(3);
	    zoomLevelContributions.add(ZoomManager.FIT_ALL);
	    zoomLevelContributions.add(ZoomManager.FIT_WIDTH);
	    zoomLevelContributions.add(ZoomManager.FIT_HEIGHT);
	    zoomManager.setZoomLevelContributions(zoomLevelContributions);
//
	    double[] zoomLevels = {.10, .25, .5, .75, 1.0, 1.25, 1.5, 2.0, 2.5, 3, 4, 5};
	    zoomManager.setZoomLevels(zoomLevels);

	    IAction zoomIn = new ZoomInAction(zoomManager);
	    IAction zoomOut = new ZoomOutAction(zoomManager);
	    getActionRegistry().registerAction(zoomIn);
	    getActionRegistry().registerAction(zoomOut);
//
	    getSite().getKeyBindingService().registerAction(zoomIn);
	    getSite().getKeyBindingService().registerAction(zoomOut);

	    //ConnectionLayer connectionLayer = (ConnectionLayer) root.getLayer(LayerConstants.CONNECTION_LAYER);
	    //connectionLayer.setConnectionRouter(new BendpointConnectionRouter());

	    //connectionLayer.setConnectionRouter(new ShortestPathConnectionRouter(connectionLayer));
	    // connectionLayer.setVisible(false);

	    // Zoom
	    zoomManager.setZoom(1.0);
	    // Scroll-wheel Zoom
	    graphicalViewer.setProperty(MouseWheelHandler.KeyGenerator.getKey(SWT.CTRL), MouseWheelZoomHandler.SINGLETON);
	    graphicalViewer.setRootEditPart(root);
//	    graphicalViewer.setEditPartFactory(getEditPartFactory());
	  }
	 protected ActionRegistry actionRegistry;
	 protected ActionRegistry getActionRegistry()
	  {
	    if (actionRegistry == null)
	      actionRegistry = new ActionRegistry();
	    return actionRegistry;
	  }
	 protected DefaultEditDomain getEditDomain()
	  {
	    return editDomain;
	  }

	private void createSourcePage() {
//		structuredTextEditor = new StructuredTextEditor();
//		try {
//			int index = addPage(structuredTextEditor, getEditorInput());
//			setPageText(index, "source");
//			structuredTextEditor.update();
//			structuredTextEditor.setEditorPart(this);
//			// control property sheet
//			structuredTextEditor.addPropertyListener(this);
//			firePropertyChange(PROP_TITLE);
//		} catch (PartInitException e) {
//			ErrorDialog.openError(getSite().getShell(),
//					"Error creating nested text editor", null, e.getStatus()); //$NON-NLS-1$
//		}
	}

	protected ScrollingGraphicalViewer getGraphicalViewer() {
		DesignViewGraphicalViewer viewer = new DesignViewGraphicalViewer(this,
				null);
		viewer.addInputChangdListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				IStructuredSelection input = (IStructuredSelection) event
						.getSelection();
				// floatingToolbar.refresh(isTableOfContentsApplicable(input
				// .getFirstElement()));
			}
		});
		// Workaround bug 227687 An edit part's focus state is not updated
		// properly
		// Once this is bug is fixed, we can remove custom selection manager
		// viewer.setSelectionManager(new CustomSelectionManager());
		return viewer;
	}

	// public CommonSelectionManager getSelectionManager()
	// {
	// if (selectionProvider == null)
	// {
	// selectionProvider = new CommonSelectionManager(this);
	// }
	// return selectionProvider;
	// }

	protected Composite createGraphPageComposite() {
		Composite parent = new Composite(getContainer(), SWT.NONE);
		parent.setLayout(new FillLayout());
		return parent;
	}

	protected CommandStack getCommandStack() {
		return editDomain.getCommandStack();
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
//		structuredTextEditor.doSave(monitor);
		getCommandStack().markSaveLocation();
	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isSaveAsAllowed() {
		return true;
	}

	public void propertyChanged(Object source, int propId) {
		// TODO Auto-generated method stub
		
	}

}